package com.wuliupai.delivery.wuliupaidelivery.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AlertDialog;
import android.util.Base64;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.gprinter.aidl.GpService;
import com.gprinter.command.EscCommand;
import com.gprinter.command.GpCom;
import com.gprinter.command.LabelCommand;
import com.gprinter.io.GpDevice;
import com.gprinter.io.PortParameters;
import com.gprinter.save.PortParamDataBase;
import com.gprinter.service.GpPrintService;
import com.wuliupai.delivery.wuliupaidelivery.App;
import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.constants.Value;
import com.wuliupai.delivery.wuliupaidelivery.utils.LogUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.StringUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.apache.commons.lang.ArrayUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/**
 * Descriptions：打印标签页面
 * <p>
 * Author：ChenME
 * Date：11/18/2016
 * Email：ibelieve1210@163.com
 */

@EActivity(R.layout.activity_print_label)
public class PrintLabelActivity extends AppBaseActivity {

    @ViewById(R.id.tv_title)
    TextView tv_title;
    @ViewById(R.id.et_totalNumber)
    EditText et_totalNumber;
    @ViewById(R.id.tv_toPerson)
    TextView tv_toPerson;
    @ViewById(R.id.tv_toPhone)
    TextView tv_toPhone;
    @ViewById(R.id.tv_toAddress)
    TextView tv_toAddress;

    @Extra("orderCode")
    String orderCode = "";//订单编号

    @Extra("fromPerson")
    String fromPerson = "";//发货人
    @Extra("fromPhone")
    String fromPhone = "";//发货电话
    @Extra("fromAddress")
    String fromAddress = "";//发货地址

    @Extra("toPerson")
    String toPerson = "";//收货人
    @Extra("toPhone")
    String toPhone = "";//收货电话
    @Extra("toAddress")
    String toAddress = "";//收货地址

    @Extra("goodsName")
    String goodsName;//货物名称
    @Extra("weight")
    String weight;//货物重量
    @Extra("volume")
    String volume;//货物体积

    @Extra("endWarehouse")
    String endWarehouse;//目的仓

    @Extra("orderCnt")
    String orderCnt = "";//订单的件数

    private static final int INTENT_PORT_SETTINGS = 0;

    private static final int MAIN_QUERY_PRINTER_STATUS = 0xfe;//查询打印机状态的广播请求码

    private static final int TYPE_BLUETOOTH_ERR = 1;//蓝牙连接错误
    private static final int TYPE_PRINTER_ERR = 2;//打印机错误
    private static final int TYPE_COMMAND_ERR = 3;//打印机命令错误

    private final int TextLimit = 16;//每行最大字数限制
    private final int LargeTextLimit = 11;//每行最大字数限制
    private final int TIME_OUT = 500;//查询打印机状态的超时时间

    private GpService mGpService = null;
    private PrinterServiceConnection conn = null;

    private int mPrinterIndex = 0;//打印机的编号

    private ProgressDialog progressDialog = null;//进度对话框
    private AlertDialog.Builder builder;

    private int copies = 1;//打印的份数
    private boolean isPrint = true;//是否是打印（打印/标签复位）

    /**
     * 监听打印机状态的广播接收器
     */
    private BroadcastReceiver printerStatusBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (GpCom.ACTION_CONNECT_STATUS.equals(action)) {
                int type = intent.getIntExtra(GpPrintService.CONNECT_STATUS, 0);

                LogUtils.log("打印机状态：" + type + "\n0表示无效，2表示连接中，3表示连接结束，4表示打印机无效，5表示可用");
                switch (type) {
                    case GpDevice.STATE_CONNECTING://2 连接中
                        showProgressDialog("设备连接中");
                        LogUtils.log("设备连接中");
                        break;

                    case GpDevice.STATE_NONE://0 无效
                    case GpDevice.STATE_INVALID_PRINTER://4 打印机无效
                        dismissProgressDialog();
                        showErrDialog(TYPE_PRINTER_ERR);
                        break;

                    case GpDevice.STATE_VALID_PRINTER://5 打印机有效
                        dismissProgressDialog();
                        matchPrinterState();
                        break;
                }
            } else if (GpCom.ACTION_DEVICE_REAL_STATUS.equals(action)) {//查询打印机状态
                // 业务逻辑的请求码，对应哪里查询做什么操作
                int requestCode = intent.getIntExtra(GpCom.EXTRA_PRINTER_REQUEST_CODE, -1);
                // 判断请求码，是则进行业务操作
                if (requestCode == MAIN_QUERY_PRINTER_STATUS) {
                    int status = intent.getIntExtra(GpCom.EXTRA_PRINTER_REAL_STATUS, 16);
                    String str = "打印机 ";
                    switch (status) {
                        case GpCom.STATE_NO_ERR:
                            str += "正常";
                            if (isPrint) {
                                printMultipleLabel();
                            } else {
                                goHome();
                            }
                            break;
                        case GpCom.STATE_OFFLINE:
                            str += "脱机";
                            break;
                        case GpCom.STATE_PAPER_ERR:
                            str += "缺纸";
                            break;
                        case GpCom.STATE_COVER_OPEN:
                            str += "打印机开盖";
                            break;
                        case GpCom.STATE_ERR_OCCURS:
                            str += "打印机出错";
                            break;
                        case GpCom.STATE_TIMES_OUT:
                            str += "查询超时";
                            if (isPrint) {
                                printMultipleLabel();
                            } else {
                                goHome();
                            }
                            break;
                    }
                    LogUtils.log("打印机：" + mPrinterIndex + " 状态：" + str);
                }
            }
        }
    };

    /**
     * 显示进度对话框
     *
     * @param msg
     */
    private void showProgressDialog(String msg) {
        if (null == progressDialog) {
            progressDialog = new ProgressDialog(PrintLabelActivity.this);
            progressDialog.setMessage(msg);
            progressDialog.setCancelable(false);
            progressDialog.show();
        }
    }


    @AfterViews
    void onPageStart() {
        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        initData();
        connection();
        registerPrinterStatusBroadcast();
    }

    private void initData() {
        fromPhone = StringUtils.splitString(fromPhone, "-", StringUtils.SPLIT_TYPE_1);
        toPhone = StringUtils.splitString(toPhone, "-", StringUtils.SPLIT_TYPE_1);

        tv_toPerson.setText(toPerson);
        tv_toPhone.setText(toPhone);
        tv_toAddress.setText(toAddress);
        tv_title.setText(getString(R.string.string_printLabel_orderCode) + " " + orderCode);
    }

    /**
     * 获取打印机状态
     *
     * @return -1：没有打印机连接
     * 0/1/2：连接的打印机ID
     */
    private int getPrinterConnectState() {
        int state = -1;
        for (int i = 0; i < GpPrintService.MAX_PRINTER_CNT; i++) {
            try {
                if (mGpService.getPrinterConnectStatus(i) == GpDevice.STATE_CONNECTED) {
                    return i;
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        return state;
    }

    /**
     * 查询打印机状态
     */
    private void matchPrinterState() {
        try {
            int type = mGpService.getPrinterCommandType(mPrinterIndex);//获取打印机的命令类型
            if (type == GpCom.LABEL_COMMAND) {//使用TSC命令打印标签

                mGpService.queryPrinterStatus(mPrinterIndex, TIME_OUT, MAIN_QUERY_PRINTER_STATUS);
            } else {
                showErrDialog(TYPE_COMMAND_ERR);
                LogUtils.log("使用ESC命令打印发票~~");
            }
        } catch (RemoteException e1) {
            e1.printStackTrace();
            LogUtils.log("异常~~~" + e1.toString());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == INTENT_PORT_SETTINGS) {//配置连接
            if (resultCode == RESULT_OK) {
                PortParameters mPortParam = new PortParameters();

                Bundle bundle = data.getExtras();
                int portType = bundle.getInt(GpPrintService.PORT_TYPE);
                mPortParam.setPortType(portType);
                String bluetoothAdd = bundle.getString(GpPrintService.BLUETOOT_ADDR);
                mPortParam.setBluetoothAddr(bluetoothAdd);
                if (portType == PortParameters.BLUETOOTH) {
                    if (!"".equals(bluetoothAdd)) {
                        PortParamDataBase database = new PortParamDataBase(this);
                        database.deleteDataBase("" + mPrinterIndex);
                        database.insertPortParam(mPrinterIndex, mPortParam);

                        int rel = 0;
                        try {
                            rel = mGpService.openPort(mPrinterIndex, mPortParam.getPortType(), mPortParam.getBluetoothAddr(), 0);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                            showErrDialog(TYPE_BLUETOOTH_ERR);
                        }
                        GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rel];
                        if (r != GpCom.ERROR_CODE.SUCCESS) {
                            if (r == GpCom.ERROR_CODE.DEVICE_ALREADY_OPEN) {
                                mPortParam.setPortOpenState(true);
                            } else {
                                App.toast(GpCom.getErrorText(r));
                            }
                        }
                    } else {
                        showErrDialog(TYPE_PRINTER_ERR);
                    }
                } else {
                    showErrDialog(TYPE_PRINTER_ERR);
                }

            } else {
                showErrDialog(TYPE_PRINTER_ERR);
            }
        }
    }

    /**
     * 显示错误提示对话框
     *
     * @param errType 错误类型
     */
    private void showErrDialog(int errType) {
        if (null == builder) {
            builder = new AlertDialog.Builder(this);
        }
        switch (errType) {
            case TYPE_BLUETOOTH_ERR:
                builder.setTitle("蓝牙连接失败")
                        .setMessage("请尝试重启打印机或重启蓝牙。");
                break;
            case TYPE_PRINTER_ERR:
                builder.setTitle("打印机连接失败")
                        .setMessage("请确保打印机不被其他设备连接或尝试重启打印机。");
                break;
            case TYPE_COMMAND_ERR:
                builder.setTitle("打印机模式错误")
                        .setMessage("请参照以下步骤重设打印机模式：\n" +
                                "1. 关闭打印机，同时按住电源键、FEED和FUNC键开机；\n" +
                                "2. 待指示灯依次点亮后，松开电源键，继续按住FEED和FUNC键，直到打印出当前模式为标签；\n" +
                                "3. 如果打印出当前模式为票据，则重复以上步骤重新操作。");
                break;
        }
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                builder = null;
            }
        }).show();
    }


    /**
     * 将数据发送到打印机
     * <p>
     */
    private void printMultipleLabel() {

        LabelCommand tsc = new LabelCommand();

        //设置标签间隙，按照实际尺寸设置，如果为无间隙纸则设置为0
        tsc.addGap(2);

        //设置打印浓度
        tsc.addDensity(LabelCommand.DENSITY.DNESITY12);

        //设置打印方向和镜像
        tsc.addDirection(
                LabelCommand.DIRECTION.BACKWARD,//打印方向
                LabelCommand.MIRROR.NORMAL);//是否镜像

        //设置原点坐标
        tsc.addReference(0, 0);

        //撕纸模式开启
        tsc.addTear(EscCommand.ENABLE.ON);

        //清除打印缓冲区
        tsc.addCls();

        final int unitSwitchRate = 8;//单位转换的进率（即1mm为8个点）

        int labelWidth = 73 * unitSwitchRate;//标签的宽度
        int labelHeight = 99 * unitSwitchRate;//标签的高度
        int textHeight = 4 * unitSwitchRate;//文字的高度
        int textBigHeight = 7 * unitSwitchRate;//文字的高度
        int labelMidX = labelWidth / 2;//标签的中间的X坐标位置

        List<String> addressList = new ArrayList<>();

        int marginX = 10,
                marginY = 2 * unitSwitchRate;//标签的xy边距(单位：dot)
        int lineWidth = 2;//分割线的宽度
        int spaceHeight = 10;//空白分割区的高度

        int labelHeightTemp = marginY;//临时的标签的高度，用于绘制过程中定位位置使用（单位：dot）

        /** ******************* 绘制四周的边框 start ********************* */
        //左上角起点point
        int leftTopX = marginX;
        int leftTopY = marginY;

        //右上角起点point
        int rightTopX = labelWidth - marginX - lineWidth;
        int rightTopY = marginY;

        //左下角起点point
        int leftBottomX = marginX;
        int leftBottomY = labelHeight - 2 * marginY;

        int borderWidth = labelWidth - 2 * marginX;//横向边框线的宽度
        int contentStartX = leftTopX + unitSwitchRate + lineWidth;//标签内容开始的X坐标

        //绘制四周的边框
        tsc.addBar(leftTopX, leftTopY, borderWidth, lineWidth);//上线
        tsc.addBar(leftBottomX, leftBottomY, borderWidth, lineWidth);//下线
        tsc.addBar(leftTopX, leftTopY, lineWidth, labelHeight - 2 * marginY);//左线
        tsc.addBar(rightTopX, rightTopY, lineWidth, labelHeight - 2 * marginY);//右线

        labelHeightTemp += spaceHeight + lineWidth;
        /** ******************** 绘制四周的边框 end ********************** */


        /** ******************* 绘制Logo start ********************* */
        // 绘制图片
        Bitmap b = BitmapFactory.decodeResource(getResources(), R.mipmap.logo);
        tsc.addBitmap(contentStartX, marginY + spaceHeight,
                LabelCommand.BITMAP_MODE.OVERWRITE, 213, b);
        /** ******************** 绘制Logo end ********************** */


        /** ******************* 绘制条码 start ********************* */
        int barcodeHeight = 14 * unitSwitchRate;//条形码的高度
        int barcodeWith = 40 * unitSwitchRate;//条形码的宽度
        int barcodeStartX = rightTopX - spaceHeight - barcodeWith;

        tsc.add1DBarcode(
                barcodeStartX,//起始横坐标
                labelHeightTemp,//起始纵坐标
                LabelCommand.BARCODETYPE.CODE128,//条码类型
                barcodeHeight,//条码高度
                LabelCommand.READABEL.EANBEL,//是否打印可识别字符
                LabelCommand.ROTATION.ROTATION_0,//条码旋转角度 0 90 180 270
                orderCode);//条码数据，数据需参考条码规则输入
        labelHeightTemp += barcodeHeight;//打印条码结束后，高度加上条码下面的文字高度
        labelHeightTemp += spaceHeight + 3 * unitSwitchRate;

        tsc.addBar(leftTopX, labelHeightTemp, borderWidth, lineWidth);
        labelHeightTemp += lineWidth + spaceHeight;
        /** ******************** 绘制条码 end ********************** */


        /** ******************* 绘制目的仓 start ********************* */
        drawText(tsc, contentStartX, labelHeightTemp, endWarehouse, true);
        labelHeightTemp += textBigHeight;

        tsc.addBar(leftTopX, labelHeightTemp, borderWidth, lineWidth);
        labelHeightTemp += lineWidth + spaceHeight;
        /** ******************** 绘制目的仓 end ********************** */


        /** ******************* 绘制货物信息（名称、重量、体积、件数） start ********************* */
        int goodsInfoHeight = 2 * textHeight + 2 * spaceHeight;//货物信息（名称、重量、体积、件数）区域的高度

        //件数与货物重量名称之间的分割线
        tsc.addBar(labelMidX, labelHeightTemp - spaceHeight, lineWidth, goodsInfoHeight);

        //货物件数
        drawText(tsc, contentStartX + 17 * unitSwitchRate, labelHeightTemp + spaceHeight, orderCnt, true);

        //货物名称
        drawText(tsc, labelMidX + spaceHeight, labelHeightTemp, goodsName, false);
        labelHeightTemp += textHeight + spaceHeight;

        //货物重量体积
        drawText(tsc, labelMidX + 2 * spaceHeight, labelHeightTemp, weight + " " + volume, false);
        labelHeightTemp += textHeight;

        tsc.addBar(leftTopX, labelHeightTemp, borderWidth, lineWidth);
        labelHeightTemp += lineWidth;
        /** ******************** 绘制货物信息（名称、重量、体积、件数） end ********************** */


        /** ******************* 绘制目的地 start ********************* */
        //派送信息
        labelHeightTemp += 4;
        drawText(tsc, contentStartX, labelHeightTemp, "派送信息", false);
        labelHeightTemp += textHeight;

        addressList.clear();
        addressList = StringUtils.splitStringByLength(toAddress, LargeTextLimit);
        addressList.add(toPerson + " " + toPhone);
        for (int i = 0; i < addressList.size(); i++) {
            drawText(tsc, contentStartX, labelHeightTemp + (i * textBigHeight), addressList.get(i), true);
        }
        labelHeightTemp += 4 * textBigHeight;//文字按4行处理
        tsc.addBar(leftTopX, labelHeightTemp, borderWidth, lineWidth);
        /** ******************** 绘制目的地 end ********************** */


        /** ******************* 绘制发货信息 start ********************* */
        labelHeightTemp += 4;
        int qrCodeWidth = (int) 16.5 * unitSwitchRate;//二维码的宽度
        int qrCodeStartX = rightTopX - spaceHeight - qrCodeWidth;//二维码绘制的X坐标

        //二维码
        tsc.addQRCode(
                qrCodeStartX,//起始横坐标`
                labelHeightTemp + spaceHeight,//起始纵坐标
                LabelCommand.EEC.LEVEL_L,//纠错级别
                4,//单元大小
                LabelCommand.ROTATION.ROTATION_0,//旋转角度  0 90 180 270
                Value.LabelHeaderFlag + orderCode);
        int dividerHeight = qrCodeWidth + 4 * spaceHeight;

        //二维码与货物重量名称之间的分割线
        tsc.addBar(qrCodeStartX - spaceHeight - lineWidth, labelHeightTemp - 4, lineWidth, dividerHeight);


        //发货信息
        drawText(tsc, contentStartX, labelHeightTemp, "发货信息", false);
        labelHeightTemp += textHeight;

        addressList.clear();
        addressList = StringUtils.splitStringByLength(fromAddress, TextLimit);
        addressList.add(fromPerson + " " + fromPhone);
        for (int i = 0; i < addressList.size(); i++) {
            drawText(tsc, contentStartX, labelHeightTemp + (i * textHeight), addressList.get(i), false);
        }
        /** ******************** 绘制发货信息 end ********************** */

        //设置标签的尺寸（单位mm）
        tsc.addSize(labelWidth / unitSwitchRate, labelHeight / unitSwitchRate);

        tsc.addPrint(copies, 1); // 打印标签

        //设置蜂鸣器
        tsc.addSound(
                2,//声音阶级
                100);//声音阶级

        //产生钱箱控制脉冲
        tsc.addCashdrwer(
                LabelCommand.FOOT.F5,//钱箱引脚号
                255,//高电平时间为 t1 x 2ms
                255);//低电平时间为t2 x 2ms

        Vector<Byte> datas = tsc.getCommand(); // 发送数据
        Byte[] Bytes = datas.toArray(new Byte[datas.size()]);
        byte[] bytes = ArrayUtils.toPrimitive(Bytes);
        String str = Base64.encodeToString(bytes, Base64.DEFAULT);
        int rel;
        try {
            rel = mGpService.sendLabelCommand(mPrinterIndex, str);
            GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rel];
            if (r != GpCom.ERROR_CODE.SUCCESS) {
                Toast.makeText(getApplicationContext(), GpCom.getErrorText(r), Toast.LENGTH_SHORT).show();
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }

        onBackPressed();
    }


    /**
     * 绘制文字
     *
     * @param tsc     指令对象
     * @param x       绘制起点X
     * @param y       绘制起点Y
     * @param content 文字内容
     * @param isBig   是否启用大字体
     */
    private void drawText(LabelCommand tsc, int x, int y, String content, boolean isBig) {
        LabelCommand.FONTMUL fontmul = LabelCommand.FONTMUL.MUL_1;
        if (isBig) {
            fontmul = LabelCommand.FONTMUL.MUL_2;
        }
        tsc.addText(
                x, //起始横坐标
                y,//起始纵坐标
                LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE,//字体类型
                /**
                 * enum FONTTYPE {
                 *  FONT_1("1"),    8x12 dot 英文和数字
                 *  FONT_2("2"),    12x20 dot 英文和数字
                 *  FONT_3("3"),    16x24 dot 英文和数字
                 *  FONT_4("4"),    24x32 dot 英文和数字
                 *  FONT_5("5"),    32x48 dot 英文和数字
                 *  FONT_6("6"),    14x19 dot 英文和数字
                 *  FONT_7("7"),    21x27 dot 英文和数字
                 *  FONT_8("8"),    14x25 dot 英文和数字
                 *  SIMPLIFIED_CHINESE("TSS24.BF2"),   简体中文
                 *  TRADITIONAL_ CHINESE ("TST24.BF2"),    繁体中文
                 *  KOREAN("K");                  韩文
                 * }
                 */
                LabelCommand.ROTATION.ROTATION_0,//旋转角度 0 90 180 270
                fontmul,//横向放大系数 1-10倍
                fontmul,//纵向放大系数1-10倍
                content);
    }


    /**
     * 连接服务
     */
    private void connection() {
        conn = new PrinterServiceConnection();
        Intent intent = new Intent(this, GpPrintService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE); // bindService
    }

    /**
     * 注册监听打印机状态的广播接收器
     */
    private void registerPrinterStatusBroadcast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(GpCom.ACTION_CONNECT_STATUS);
        filter.addAction(GpCom.ACTION_DEVICE_REAL_STATUS);
        this.registerReceiver(printerStatusBroadcastReceiver, filter);
    }

    /**
     * 关闭进度对话框
     */
    private void dismissProgressDialog() {
        if (null != progressDialog) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    /**
     * 打印标签
     */
    @Click(R.id.btn_confirmPrintBtn)
    void printLabel() {
        try {
            copies = Integer.parseInt(et_totalNumber.getText().toString().trim());
        } catch (NumberFormatException nfe) {
            copies = 1;
        }
        copies = copies <= 0 ? 1 : copies;
        connectPrintIfNot(true);
    }

    /**
     * 如果没有连接打印机则进行连接
     */
    void connectPrintIfNot(boolean isPrint) {
        dismissProgressDialog();
        this.isPrint = isPrint;
        //获取打印机连接状态
        if (-1 == getPrinterConnectState()) {
            //没有打印机连接
            Intent intent = new Intent(this, PortConfigurationActivity_.class);
            startActivityForResult(intent, INTENT_PORT_SETTINGS);
        } else {
            matchPrinterState();
        }
    }

    /**
     * 标签复位
     */
    @Click(R.id.btn_resetBtn)
    void resetLabel() {
        connectPrintIfNot(false);
    }

    /**
     * 开始复位
     */
    private void goHome() {
        LabelCommand tsc = new LabelCommand();
        //设置标签间隙，按照实际尺寸设置，如果为无间隙纸则设置为0
        tsc.addGap(2);

        //设置打印方向和镜像
        tsc.addDirection(
                LabelCommand.DIRECTION.BACKWARD,//打印方向
                LabelCommand.MIRROR.NORMAL);//是否镜像

        //撕纸模式开启
        tsc.addTear(EscCommand.ENABLE.ON);

        //清除打印缓冲区
        tsc.addCls();
        tsc.addHome();

        //产生钱箱控制脉冲
        tsc.addCashdrwer(
                LabelCommand.FOOT.F5,//钱箱引脚号
                255,//高电平时间为 t1 x 2ms
                255);//低电平时间为t2 x 2ms

        Vector<Byte> datas = tsc.getCommand(); // 发送数据
        Byte[] Bytes = datas.toArray(new Byte[datas.size()]);
        byte[] bytes = ArrayUtils.toPrimitive(Bytes);
        String str = Base64.encodeToString(bytes, Base64.DEFAULT);
        int rel;
        try {
            rel = mGpService.sendLabelCommand(mPrinterIndex, str);
            GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rel];
            if (r != GpCom.ERROR_CODE.SUCCESS) {
                App.toast(GpCom.getErrorText(r));
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 退出
     */
    @Click(R.id.iv_finishBtn)
    void finishPage() {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        animUtils.popOutAnimation(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != printerStatusBroadcastReceiver) {
            unregisterReceiver(printerStatusBroadcastReceiver);
        }
        try {
            //在解除绑定时，该方法会被系统多次调用，会出现异常
            if (null != conn) {
                unbindService(conn);
            }
        } catch (IllegalArgumentException iae) {
            iae.printStackTrace();
        }

    }

    /**
     * 连接服务
     */
    class PrinterServiceConnection implements ServiceConnection {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("ServiceConnection", "onServiceDisconnected() called");
            mGpService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mGpService = GpService.Stub.asInterface(service);
//            isServiceConnected = true;
        }
    }
}